import Vue from "vue";
import Vuex from "vuex";
import router from "@/router"
// import * as  permissionApi from "@/api/permissions"
import * as permissApi from "@/api/permission"
import recursionRoutes from "@/utils/recursionRoutes"
import allRoutes from "@/router/generateRoutes"
import dynamicRoutes from "@/router/dynamicRoutes"
//引入持久化存储
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userMenu: [],
    userInfo:{},//用户信息
    currentProduct:{},//当前充值的产品对象
    breadCrumb:[]//面包屑
  },
  getters: {},
  mutations: {
    //设置用户菜单
    SET_MENULIST(state, payload) {
      state.userMenu = [...payload] //浅拷贝
      //动态添加路由
      let target = dynamicRoutes.find(route => route.path === "/");
      target.children = [...target.children, ...payload]

      router.addRoute(target)
    },
    //修改用户信息
    SET_USERINFO(state,payload){
      state.userInfo=payload
    },
    //设置当前充值的产品
    SET_CURRENT_PRODUCT(state, payload) {
      state.currentProduct = payload
    },
    //表格显示loading动画
    SHOW_LOADING(state) {
      state.loading = true;
    },
    //表格隐藏loading动画
    HIDE_LOADING(state) {
      state.loading = false;
    },
    //设置学员项目管理表格中的数据
    SET_STU_DATA(state, payload) {
      state.stuData = payload.data;//设置学员列表
      state.loading = false;//关闭加载动画
      state.stuTotal = payload.total;//设置学员分页总数
    },
    //显示diglog
    SHOW_DIALOG(state) {
      state.dialogVisible = true;
    },
    //隐藏dialog
    HIDE_DIALOG(state) {
      state.dialogVisible = false
    },
    //修改dialog标题
    CHANGE_DIALOG_TITLE(state, payload) {
      state.dialogTitle = payload;
    },
    //保存用户信息
    SET_USER_INFO(state, payload) {//设置用户信息
      state.userInfo = payload;
    },
    SET_BREADCRUMB(state, payload) {//设置面包屑
      state.breadCrumb = payload;
    },
  },
  actions: {
    //获取学员列表
    GET_STULIST({ commit }, payload = {}) {
      commit("SHOW_LOADING")//打开加载动画
      let { page = 1, count = 10, classes = "" } = payload;//解构传递的参数
      api.getStuListApi(page, count, classes)
        .then(res => {
          commit("SET_STU_DATA", res.data)
        })
    },
    async FETCH_MENULIST(context, payload) {
      return permissApi.getMenuList().then(res => {
        // console.log(res)
        let {
          menuList
        } = res.data;
        let userRoutes = recursionRoutes(allRoutes[0].children, menuList)
        // console.log(userRoutes)
        context.commit("SET_MENULIST", userRoutes)
      })
    }
  },
  modules: {},
   /* vuex数据持久化配置 */
   plugins: [
    createPersistedState({
      // 存储方式：localStorage、sessionStorage、cookies
      storage: window.localStorage,
      // 存储的 key 的key值
      key: "myx2",
      paths: ['userInfo', 'currentProduct']
    })
  ]
});